package com.yxx.community.provider;

import com.alibaba.fastjson.JSON;
import com.yxx.community.dto.AccessTokenDTO;
import com.yxx.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 11:41 2020/1/26
 **/
@Component
public class GithubProvider {

  public String getAccessToken(AccessTokenDTO accessTokenDTO){
    MediaType mediaType= MediaType.get("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
      RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDTO));
      Request request = new Request.Builder()
              .url("https://gitee.com/oauth/token")
              .post(body)
              .build();
      try (Response response = client.newCall(request).execute()) {
        String string = response.body().string();
        String access_token = string.split(",")[0].split(":")[1].replace("\"", "");
        return access_token;
      } catch (IOException e) {
      }
      return null;
  }

  public GiteeUser getUser(String access_token){
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url("https://gitee.com/api/v5/user?access_token="+access_token)
            .build();
    try{
      Response response = client.newCall(request).execute();
      String string=response.body().string();
      GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
      return giteeUser;
    }catch(Exception e){
      return null;
    }
  }
}
